import { UserInfoType } from "./../types/user.d";
import { defineStore } from "pinia";
import { ref } from "vue";
import { userLogin, roleGet } from "../api/user";
import { AccountType } from "../types/user";
import router from "../router";

export const useAccount = defineStore(
  "user",
  () => {
    const userInfo = ref<UserInfoType | null>(null);
    const loginAction = async (account: AccountType) => {
      // 发起登录请求
      let res = await userLogin(account);
      // 得到后端下发的用户信息，为userInfo赋值
      if (res.status == 200) {
        let role = await roleGet(res.data.roleId); //使用角色id，获取角色权限
        userInfo.value = {
          ...res.data, //用户信息
          ...role.data, //角色信息
        };
        //触发路由跳转
        router.push("/");
      }
    };
    return {
      userInfo,
      loginAction,
    };
  },
  { persist: { key: "userinfo-2304" } }
);
